<template>
  <div style="">
    <el-table
      ref="elTable"
      :key="headKey"
      v-loading="loading"
      :default-sort="{ prop: 'cost', order: 'descending' }"
      :row-style="{ height: '20px' }"
      :height="
        tableHeight == 0
          ? 'calc(100vh - 180px)'
          : this.showAllFilterCondition
            ? 'calc(100vh - 180px)'
            : 'calc(100vh - 138px)'
      "
      border
      style="width: 100%"
      v-bind="$attrs"
      :row-class-name="rowClass"
      tooltip-effect="light"
      :show-summary="false"
      :summary-method="getSummaries"
      v-on="$listeners"
      @header-dragend="headerDragend"
      @selection-change="handleSelectionChange"
      @sort-change="sort_change"
    >
      <el-table-column type="selection" width="55" />

      <!-- 循环表头 -->
      <template v-for="(col, index) in tableHead">
        <template v-if="col.prop === 'oper'">
          <el-table-column
            v-if="col.show"
            :key="index"
            :show-overflow-tooltip="true"
            :prop="col.prop"
            label="操作"
            :align="col.align || 'center'"
            :min-width="col.width || 100"
          >
            <template slot="header" slot-scope="{ column, $index }">
              <span style="cursor: pointer">
                {{ col.label }}
              </span>
            </template>
            <template slot-scope="{ row, column, $index }">
              <el-button
                size="mini"
                type="danger"
                style="margin-right: 10px"
                @click="openComment(row, column, $index)"
              >{{
                row.comment_control == true ? "关控评" : "开控评"
              }}</el-button>
              <el-button
                size="mini"
                type="danger"
                style="margin-right: 10px"
                @click="openComments(row,column, $index)"
              >{{
                row.is_comment_auto_reply_open == true ? "关闭自动回复" : "开启自动回复"
                }}</el-button>
            </template>
          </el-table-column>
        </template>
        <template v-else-if="col.prop === 'operas'">
          <el-table-column
            v-if="col.show"
            :key="index"
            :show-overflow-tooltip="true"
            :prop="col.prop"
            label="操作"
            :align="col.align || 'center'"
            :min-width="col.width"
          >
            <template slot-scope="{ row,column, $index}">
              <el-button
                size="mini"
                type="danger"
                style="margin-right: 10px"
                @click="openComment(row,column, $index)"
              >{{
                row.is_comment_control == true ? "关闭控评" : "开启控评"
              }}</el-button>
              <el-button
                size="mini"
                type="danger"
                style="margin-right: 10px"
                @click="openComments(row,column, $index)"
              >{{
                row.is_comment_auto_reply_open == true ? "关闭自动回复" : "开启自动回复"
                }}</el-button>
            </template>
          </el-table-column>
        </template>
         <template v-else-if="col.prop === 'oper_comment'">
          <el-table-column
            v-if="col.show"
            :show-overflow-tooltip="true"
            :key="index"
            :prop="col.prop"
            label="操作"
            :align="col.align || 'center'"
            :min-width="col.width || 100"
          >
            <template slot-scope="{ row }">
              <el-button
                size="mini"
                type="primary"
                style="margin-right: 10px"
                @click="modifyUserNote(row,'reply')"
              >回复评论</el-button
              >
              <el-dropdown trigger="click" @command="handleCommand">
                <el-button size="mini" type="success"> 更多 </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    :command="beforeHandleCommand(row, 'top')"
                  >置顶评论</el-dropdown-item
                  >
                  <el-dropdown-item
                    divided
                    :command="beforeHandleCommand(row, 'conceal')"
                  >隐藏评论</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>

            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column
            v-if="col.show"
            :key="index"
            :show-overflow-tooltip="true"
            :min-width="col.width || 100"
            :prop="col.prop"
            :align="col.align || 'center'"
            :label="col.label"
            :fixed="col.prop === 'name' ||
              col.prop === 'account' ||
              col.prop === 'advertiser_id'
            "
            :sortable="col.sortable === true ? 'custom' : false
            "
          >
            <!-- <template slot="header" slot-scope="{ column, $index }">
              <span style="cursor: pointer">
                {{ col.label }}
              </span>
            </template> -->
            <template slot-scope="{ row }">
              <div v-if="col.prop === 'name'">
                <!--  <span
                  style="cursor: pointer; color: #409eff"
                  @click="
                    openNewTabByIframe(
                      row.advertiser_id,
                      row.ad_user_id,
                      row.name
                    )
                  "
                  >{{ row.name }}</span
                >-->
                {{ row.name }}
              </div>
              <div
                v-else
                :style="{
                  cursor:
                    col.prop === 'cost' || col.prop === 'note'
                      ? 'pointer'
                      : null,
                }"
                @dblclick="modifyUserNote(row, col.prop)"
              >
                {{ row[col.prop] }}
              </div>
            </template>
          </el-table-column>
        </template>
      </template>
    </el-table>
    <custom-columns-modal
      ref="customRef"
      :data="tableHead"
      @changeColums="changeColums"
    />
    <el-dialog :visible.sync="dialogVisible" width="95%" :fullscreen="true">
      <div style="color: red; margin-bottom: 10px; position: absolute; top: 0">
        右上角点击关闭
        <p style="color: black; font-weight: 700">
          {{ title }}
        </p>
      </div>
      <!-- 在弹窗中显示的页面内容 -->
      <iframe
        ref="iframe"
        frameborder="0"
        width="100%"
        height="850px"
        :src="iframeUrl"
        style="overflow: hidden"
        @load="iframeLoaded"
      />
    </el-dialog>
  </div>
</template>

<script>
import CustomColumnsModal from './customColumnsModal.vue'
import Clipboard from 'clipboard'
export default {
  components: { CustomColumnsModal },
  props: {
    showAllFilterCondition: {
      type: Boolean
    },
    headColumns: Array,
    otherTotal: {
      type: Object
    },
    loading: {
      type: Boolean,
      default: false
    },
    platForm: {
      type: Number,
      default: 1
    },
    StoreNames: {
      type: String
    }
  },

  data() {
    return {
      tableHeight: 0,
      dialogVisible: false,
      title: 'loading...',
      iframeUrl: '',
      storeName: '',
      tableHead: [],
      headKey: 'dragHead' // 表头数组变换位置时，重绘table（不更新该值，表头数组变化时，页面不会改变）
    }
  },
  watch: {

    StoreNames: {
      immediate: true,
      handler(obj) {
        // console.log(obj)
        this.storeName = obj
        if (localStorage.getItem(this.storeName)) {
          const arr = localStorage.getItem(this.storeName)
          if (JSON.parse(arr).length === 0) {
            this.tableHead = this.headColumns
            return
          }
          if (arr) {
            JSON.parse(arr).map((item) => {
              if (item !== null) {
                this.tableHead.push(item)
              }
            })
          }

          localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
        } else {
          localStorage.setItem(this.storeName, [])
          this.tableHead = this.headColumns
        }
      },
      deep: true
    },
    tableHead: {
      handler(obj) {
        const arr = []
        let tag = false
        let errIndex = 0
        obj.map((item, index) => {
          if (item === null || item === undefined) {
            errIndex = index
            tag = true
          } else {
            arr.push(item)
          }
        })
        if (tag) {
          const oriKey = this.headColumns.map((item) => {
            return item.prop
          })
          const errKey = arr.map((item) => {
            return item.prop
          })
          oriKey.map((item, index) => {
            if (!errKey.includes(item)) {
              // console.log('errCol', this.headColumns[index])
              arr.splice(errIndex, 0, this.headColumns[index])
            }
          })
          this.tableHead = arr
        }
      },
      deep: true
    }
  },
  mounted() {

  },
  updated() {
    this.$nextTick(() => {
      this.$refs.elTable.doLayout()
    })
  },
  methods: {
    copyMonitorUrl() {
      const _this = this
      const clipborad = new Clipboard('#copy')
      // 复制成功
      clipborad.on('success', function() {
        _this.$message.success('复制成功！')
        clipborad.destroy()
      })
      // 复制失败
      clipborad.on('error', function() {
        _this.$message.error('复制失败！')
        clipborad.destroy()
      })
    },
    headerDragend(newWidth, oldWidth, column, event) {
      this.tableHead.map((item) => {
        if (item.prop === column.property) {
          item.width = newWidth
        }
      })

      localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
    },
    renderTable() {
      this.tableHeight = this.showAllFilterCondition
        ? 'calc(100vh - 180px)'
        : 'calc(100vh - 138px)'
      this.$nextTick(() => {
        this.$refs.elTable.doLayout()
      })
    },
    openNewTabByIframe(id, ad_user_id, name) {
      // console.log("iframe=========", window.parent, window.location.href);
      let addressName = 'all_jihua_list_vue'
      if (window.location.href.includes('ad_list_vue_tb')) {
        addressName = 'all_jihua_list_vue_tb'
      } else {
        addressName = 'all_jihua_list_vue'
      }

      this.dialogVisible = true
      this.title = name
      // 设置弹窗中显示的页面 URL
      this.iframeUrl =
        // "page/" +
        addressName +
        '.html?advertiser_id=' +
        id +
        '&platForm=' +
        this.platForm +
        '&ad_user_id=' +
        ad_user_id
    },
    iframeLoaded() {
      const iframe = this.$refs.iframe
      const iframeWin = iframe.contentWindow
      const iframeDoc = iframeWin.document.documentElement
      const height = Math.max(
        iframeDoc.scrollHeight,
        iframeDoc.offsetHeight,
        iframeDoc.clientHeight
      )
      iframe.style.height = height + 'px'
    },
    changeColums(newData) {
      this.tableHead = []
      this.$refs.elTable.doLayout()
      setTimeout(() => {
        this.tableHead = newData
        localStorage.setItem(this.storeName, JSON.stringify(newData))
        this.$emit('fresh')
      }, 50)
    },
    openCustomModal() {
      const custom = this.$refs.customRef
      custom.dialogOpen(this.tableHead)
    },
    accAdd(arg1, arg2) {
      var r1, r2, m
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      // 解决JS浮点数精度问题
      m = Math.pow(10, Math.max(r1, r2))
      // 保留两位小数
      return parseFloat((arg1 * m + arg2 * m) / m).toFixed(2)
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map((item) => Number(item[column.property]))
        const dataTotal = [
          'effective_roi',
          'ROI',
          'convert_cost',
          'convert_rate',
          'convert'
        ]
        const needTotal = [
          'cash',
          'cost',
          'effective_sale',
          'effective_order_num',
          'sale',
          'order_num',
          'convert_rate',
          'click',
          'click_rate',
          'show',
          ...dataTotal
        ]

        if (needTotal.includes(column.property)) {
          if (dataTotal.includes(column.property)) {
            if (column.property === 'effective_roi') {
              sums[index] = this.otherTotal.effective_total_roi
            } else if (column.property === 'convert_cost') {
              sums[index] = this.otherTotal.convert_cost_total
            } else if (column.property === 'convert_rate') {
              sums[index] = this.otherTotal.convert_rate_total
            } else if (column.property === 'convert') {
              sums[index] = this.otherTotal.convert_total
            } else {
              sums[index] = this.otherTotal.total_roi
            }
          } else {
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return this.accAdd(prev, curr)
                } else {
                  return prev
                }
              }, 0)
            }
          }
        }
      })
      return sums
    },
    openHourPlanListDialog(...args) {
      this.$emit('openHourPlanListDialog', ...args)
    },
    rowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2 == 1) {
        return 'doub-row'
      }
    },

    beforeHandleCommand(row, command) {
      return {
        val: row,
        key: command
      }
    },
    handleCommand(command) {
      this.$emit('handleCommand', command)
      // console.log('command', command)
    },
    openComment(...args) {
      this.$emit('openComment', ...args)
    },
    openComments(...args) {
      this.$emit('openComments', ...args)
    },
    openModifyTwoLink(...args) {
      this.$emit('openModifyTwoLink', ...args)
    },
    openPddLinkDialog(...args) {
      this.$emit('openPddLinkDialog', ...args)
    },
    sort_change(column) {
      this.$emit('sort_change', column)
    },
    handleSelectionChange(val) {
      this.$emit('handleSelectionChange', val) /* 向外暴露set方法 */
    },

    modifyUserNote(row, prop) {
      if (prop === 'note') {
        this.$emit('handleCommand', { val: row, key: 'modify' })
      }
      if (prop === 'cost') {
        this.$emit('handleCommand', { val: row, key: 'hourList' })
      }
      if(prop==='reply'){
        this.$emit('handleCommand', { val: row, key: 'reply' })
      }
    }
  }
}
</script>

<style lang="scss">
.el-table {
  // overflow: visible !important;
  .drag_start {
    opacity: 0.8;
    background-color: rgba(0, 0, 0, 0.938);
    color: #f3e8e8fd;
    transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  }
  .drag_end_left {
    border-left: 2px dotted rgba(0, 0, 0, 0.938);
  }
  .drag_end_right {
    border-right: 2px dotted rgba(0, 0, 0, 0.938);
  }

  .doub-row {
    background: #f2f2f2;
  }
  .el-table__footer {
    // position: fixed;
    bottom: 0;
    z-index: 111;
  }
  .el-table__cell.is-hidden > * {
    visibility: visible !important;
  }
}

.el-table .cell div {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: initial;
}

/*.el-table__header th {*/
  /*padding: 0 !important;*/
/*}*/
.el-table td.el-table__cell {
  padding: 4px 0 !important;
}
.el-table--small {
  font-size: 14px !important;
}
.el-table th.el-table__cell {
  background-color: #fafafa !important;
}

/*没有固定列（通过样式属性order将body移动到后面去。默认的oder:0就排在了前面）*/
.el-table {
  display: flex;
  flex-direction: column;
}
.el-table__body-wrapper {
  order: 1;
}
/* 有固定列(需要将固定列做同样设置，由于固定列设置了position:absolute，在设置order会不生效，需要将position:initial) */
.el-table__fixed {
  display: flex;
  flex-direction: column;
}
.el-table__fixed-footer-wrapper,
.el-table__fixed-body-wrapper,
.el-table__fixed-header-wrapper {
  position: initial !important;
}

.el-table__fixed-body-wrapper {
  order: 1;
}

/* 默认有1px去掉样式影响 */
.el-table__fixed::before {
  height: 0 !important;
}

.el-table__fixed-body-wrapper .el-table__body {
  margin-top: -1px;
}

.el-table__fixed-body-wrapper,
.el-table__fixed-footer-wrapper,
.el-table__fixed-header-wrapper {
  pointer-events: auto;
}
.el-table__fixed,
.el-table__fixed-right {
  pointer-events: none !important;
}
.el-dialog__headerbtn .el-dialog__close {
  font-size: 25px;
}
</style>
